﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLite.Threading;

namespace NLite.Domain
{
    /// <summary>
    /// 工作单元接口
    /// </summary>
    public interface IUnitOfWork : IDisposable
    {
        /// <summary>
        /// 保存所有的改变到持久层
        /// </summary>
        void SaveChanges();
    }

    /// <summary>
    /// 工作单元门面类
    /// </summary>
    public static class UnitOfWork
    {
        /// <summary>
        /// 得到当前工作单元对象
        /// </summary>
        public static IUnitOfWork Current
        {
            get
            {
                var uow = current;
                if (uow == null)
                    throw new NotImplementedException("No initialize and set unit of work!");
                return uow;
            }
        }

        private static IUnitOfWork current
        {
            get
            {
                return Local.Get("UnitOfWork") as IUnitOfWork;
            }
        }

        /// <summary>
        /// 设置工作单元
        /// </summary>
        /// <param name="uow"></param>
        public static void SetUnitOfWork(IUnitOfWork uow)
        {
            if (uow == null)
                throw new ArgumentNullException("uow");
            if (current != null)
                current.Dispose();
            Local.Remove("UnitOfWork");
            Local.Set("UnitOfWork", uow);
        }

        /// <summary>
        /// 保存所有的改变到持久层
        /// </summary>
        public static void SaveChanges()
        {
            Current.SaveChanges();
        }
        
        /// <summary>
        /// 释放工作单元资源
        /// </summary>
        public static void Dispose()
        {
            var uow = current;
            if (uow != null)
            {
                try
                {
                    uow.Dispose();
                }
                catch (Exception e)
                {
                    e.Handle();
                }
            }
        }
    }
}
